from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.services.user_service import UserService
from app.schemas.user_schema import UserCreate, UserLogin
from app.schemas.common_schema import R

router = APIRouter(prefix="", tags=["认证"])

@router.post("/register", response_model=R)
def register(user: UserCreate, db: Session = Depends(get_db)):
    code, msg, user = UserService.register(db, user)
    if user:
        return R(code=code, message=msg, data={"id": user.id, "username": user.username})
    return R(code=code, message=msg, data=None)

@router.post("/login", response_model=R)
def login(form: UserLogin, db: Session = Depends(get_db)):
    code, msg, token = UserService.authenticate(db, form.username, form.password)
    if token:
        return R(code=code, message=msg, data={"access_token": token})
    return R(code=code, message=msg, data=None)